import { $xltApi } from '@front/web-basic';
import router from '@/router';
import { store } from '@/store';
import { ENTRY_PARAMS, TOKEN, USER_INFO } from '@/constants/common';
import Storage from '@/utils/storage';
import Utils from '@/utils/utils';

import { useService } from '@/utils/services';
import XltData from '@/utils/XltData';
import process from './process';

// 保存入口参数
export async function setEntryParams() {
  const entryParams = Utils.params2json(window.location.search.split('?')[1]);
  const { patientsId, hospitalId, departmentId } = Storage.get(ENTRY_PARAMS) || {};
  if (Object.keys(entryParams).length) {
    entryParams.bedNum = decodeURIComponent(entryParams.bedNum) || '';
    Storage.set(ENTRY_PARAMS, { patientsId, departmentId, hospitalId, ...entryParams });
  }
}

// 登录
export async function login() {
  // 检查床位是否限制
  if (store.getters.isDisableBed) return Promise.resolve();

  const actions = useService();
  try {
    const { patientsId, isScan } = Storage.get(ENTRY_PARAMS) || {};

    if (!patientsId) {
      throw new Error('patientsId 不存在');
    }

    let userInfo = await actions.hos.login({
      patientsId,
      anonymousId: XltData.quick('getAnonymousID')
    });
    if (userInfo.token) {
      Storage.set(USER_INFO, userInfo);
      Storage.set(TOKEN, userInfo.token);
      store.commit('setUserInfo', userInfo);
      store.commit('setToken', userInfo.token);

      $xltApi.setDefaultCommonHeader({
        common: {
          'Content-Type': 'application/json',
          token: userInfo.token
        }
      });

      // 获取科室列表
      getDeptList();

      // 加载标记组
      store.dispatch('getMark');

      // 扫码进入才会检查流程
      if (isScan) {
        // 检查流程开始
        process.init();
      }

      return Promise.resolve();
    }
  } catch (err) {
    Storage.clear();
    router.replace('/no-login');
    // 清除 操作

    return Promise.resolve(err);
  }
}

// 检查床位
export async function checkBed() {
  const actions = useService();
  try {
    const { patientsId, isScan } = Storage.get(ENTRY_PARAMS) || {};

    if (!isScan) return Promise.resolve();

    let result = await actions.hos.isQrcodeLimitPass({
      patientsId
    });

    store.commit('setIsDisableBed', !result);
    return Promise.resolve([null, true]);
  } catch (err) {
    store.commit('setIsDisableBed', true);
    return Promise.resolve([err, false]);
  }
}

export async function getDeptList() {
  const actions = useService();
  try {
    let result = await actions.hos.getDeptList();
    if (result?.length) {
      store.commit('setDeptList', result);

      setCurrentDeptInfo(result);
    }
  } catch {
    store.commit('setDeptList', []);
  }
}

function setCurrentDeptInfo(deptList) {
  let deptId = store.state.global.userInfo.departmentId;
  let currentInfo = deptList.find((item) => item.departmentId == deptId);
  if (currentInfo) {
    store.commit('setCurrentDeptInfo', currentInfo);
  }
}
